Open settings
Google Account
Khushnoor Sheikh
sameersheikhbond@gmail.com
Notebook
Code Text

Gemini

Data Types and Structure Assignment

Code Text

Gemini
  1. What are data structures, and why are they important?
  • Data structures in Python are built-in ways to store and organize data like lists, tuples, sets, and dictionaries. They are important because they let you handle data efficiently, making tasks like searching, sorting, and accessing information faster and easier.
Code Text

Gemini
  1. Explain the difference between mutable and immutable data types with examples.

Mutable Data Types

  • Can be changed or modified after creation.

  • You can update, add, or remove elements without creating a new object.

  • Examples in Python: list, set, dict

Code Text

Gemini
Code Text

Gemini

Immutable Data Types

  • Cannot be changed once created.

  • Any modification creates a new object in memory.

  • Examples in Python: int, float, string, tuple

Code Text

Gemini
Code Text

Gemini
  1. What are the main differences between lists and tuples in Python?
  • Here are the main differences between lists and tuples in Python:

  • Mutability: Lists are mutable (can be changed), Tuples are immutable (cannot be changed).

  • Syntax: Lists use square brackets [], Tuples use parentheses ().

  • Performance: Tuples are faster than lists because they are fixed.

  • Functions/Methods: Lists have more built-in methods (like append(), remove()), Tuples have fewer.

  • Use case: Lists are used when data may change, Tuples are used when data must remain constant.

Code Text

Gemini
  1. Describe how dictionaries store data?
  • In Python, a dictionary stores data in the form of key–value pairs.

  • Each item has a key (unique identifier) and a value (data associated with the key).

  • Dictionaries use a hashing mechanism, so keys are stored in a way that makes lookup very fast.

  • Keys must be immutable (like strings, numbers, or tuples), while values can be of any type.

  • Data is enclosed in curly braces {}.

Code Text

Gemini
'''
student = {"name": "Alex", "age": 20, "grade": "A"}
print(student["name"])   # Output: Alex
'''
Code Text

Gemini
  1. Why might you use a set instead of a list in Python?
  • No Duplicates Needed → Sets automatically remove duplicate values.

  • Fast Membership Checking → Checking if an item exists in a set is much faster than in a list (because sets use hashing).

  • Set Operations → Sets support mathematical operations like union (|), intersection (&), and difference (-), which lists don’t directly support.

Code Text

Gemini
'''
nums = [1, 2, 2, 3, 4]
unique_nums = set(nums)
print(unique_nums)  # Output: {1, 2, 3, 4}
'''
Code Text

Gemini
  1. What is a string in Python, and how is it different from a list?
  • A string is a sequence of characters enclosed in quotes (' ' or " ").
Code Text

Gemini
'''
text = "Hello"
'''

Code Text

Gemini

Difference between String and List

  • Data type: String stores only characters; List can store mixed data types (numbers, strings, etc.).

  • Mutability: Strings are immutable (cannot be changed after creation), Lists are mutable (can be changed).

  • Syntax: Strings use quotes, Lists use square brackets [].

  • Operations: Both support indexing and slicing, but only lists allow item assignment.

Code Text

Gemini
'''
# String (immutable)
s = "hello"
# s[0] = "H"   #  Error (strings cannot be modified)

# List (mutable)
l = ["h", "e", "l", "l", "o"]
l[0] = "H"
print(l)   # Output: ['H', 'e', 'l', 'l', 'o']
'''

Code Text

Gemini
  1. How do tuples ensure data integrity in Python?
  • Tuples ensure data integrity in Python because they are immutable, meaning once a tuple is created, its contents cannot be changed, added, or removed.

How this helps:

  • Prevents accidental modification of data.

  • Useful for storing constant values that should not be altered.

  • Can be used as keys in dictionaries because their immutability makes them hashable.

Code Text

Gemini
'''
coordinates = (10, 20)
# coordinates[0] = 15   #  Error, tuple cannot be modified
'''
Code Text

Gemini
  1. What is a hash table, and how does it relate to dictionaries in Python?
  • A hash table is a data structure that stores data in key–value pairs and uses a hash function to compute an index (called a hash) for each key. This makes data lookup, insertion, and deletion very fast.

    How it relates to Python dictionaries:

  • Python dictionaries are implemented using hash tables.

  • Each key in a dictionary is hashed to determine where its value will be stored.

  • This allows quick access to values using their keys.

  • Keys must be immutable (like strings, numbers, or tuples) so that their hash value remains constant.

Code Text

Gemini
'''
student = {"name": "Alex", "age": 20}
print(student["name"])  # Output: Alex
'''
Code Text

Gemini
  1. Can lists contain different data types in Python?
  • Yes, lists in Python can contain different data types in the same list.

  • Lists can store integers, strings, floats, booleans, or even other lists together.

  • This makes them very flexible for storing mixed data.

Code Text

Gemini
'''
 my_list = [10, "Hello", 3.14, True]
print(my_list)
# Output: [10, 'Hello', 3.14, True]
'''
Code Text

Gemini
  1. Explain why strings are immutable in Python?
  • Strings are immutable in Python because once a string is created, its contents cannot be changed.

Reasons for immutability:

  • Memory Efficiency – Immutable strings can be shared safely in memory without risk of accidental changes.

  • Hashing – Strings are hashable and can be used as dictionary keys or set elements. If they were mutable, their hash value could change, breaking data structures.

  • Safety and Predictability – Prevents accidental modification of data, ensuring consistent behavior in programs.

Code Text

Gemini
'''
s = "hello"
# s[0] = "H"   #  Error: strings cannot be modified
'''
Code Text

Gemini
  1. What advantages do dictionaries offer over lists for certain tasks?
  • Dictionaries offer several advantages over lists for certain tasks because they store data as key–value pairs:

  • Fast Lookups – Accessing a value by its key is much faster than searching through a list.

  • Unique Keys – Keys are unique, which prevents duplicate entries for identifiers.

  • Clear Mapping – Keys provide meaningful names for values, making data easier to understand.

  • Flexible Data Access – You can directly retrieve, update, or delete a value using its key instead of index.

  • Supports Complex Operations – Dictionaries are ideal for tasks like counting items, grouping data, or representing structured data.

Code Text

Gemini
'''
# Using a list
students = ["Alice", "Bob", "Charlie"]
# Find age of Bob? Need separate list or search

# Using a dictionary
students = {"Alice": 20, "Bob": 22, "Charlie": 19}
print(students["Bob"])  # Output: 22  (direct lookup)
'''
Code Text

Gemini
  1. Describe a scenario where using a tuple would be preferable over a list?
  • Coordinates should not be modified, so using a tuple ensures data integrity.

  • Tuples are also faster and can be used as dictionary keys if needed.

Code Text

Gemini
'''
location = (40.7128, -74.0060)  # New York City coordinates
'''
Code Text

Gemini
  1. How do sets handle duplicate values in Python?
  • In Python, sets automatically remove duplicate values.

  • A set stores only unique elements, so if you try to add a duplicate, it will be ignored.

  • This makes sets useful for finding unique items or eliminating duplicates from a collection.

Code Text

Gemini
'''
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)  # Output: {1, 2, 3, 4, 5}
'''
Code Text

Gemini
  1. How does the “in” keyword work differently for lists and dictionaries?
  • The in keyword is used to check if an item exists, but it works differently for lists and dictionaries in Python:

Lists

  • Checks if a value exists anywhere in the list.

  • Returns True if the value is present, False otherwise.

Code Text

Gemini
'''
my_list = [1, 2, 3]
print(2 in my_list)   # Output: True
print(5 in my_list)   # Output: False
'''
Code Text

Gemini

Dictionaries

  • Checks if a key exists in the dictionary (not the value).

  • Returns True if the key is present, False otherwise.

Code Text

Gemini
'''
my_dict = {"a": 10, "b": 20}
print("a" in my_dict)   # Output: True
print(10 in my_dict)    # Output: False  (checks keys, not values)
'''
Code Text

Gemini
  1. Can you modify the elements of a tuple? Explain why or why not?
  • No, you cannot modify the elements of a tuple in Python.

Why:

  • Tuples are immutable, meaning once a tuple is created, its contents cannot be changed, added, or removed.

  • This ensures data integrity and allows tuples to be used as dictionary keys or stored in sets.

Code Text

Gemini
'''
my_tuple = (1, 2, 3)
# my_tuple[0] = 10   # Error: tuples cannot be modified
'''

Code Text

Gemini
  1. What is a nested dictionary, and give an example of its use case?
  • A nested dictionary in Python is a dictionary where the value of a key is another dictionary. This allows you to store hierarchical or structured data.

Use Case:

Storing complex structured data, like student records, employee details, or product information.

Useful in scenarios where each key maps to multiple attributes.

Code Text

Gemini
'''
students = {
    "Alice": {"age": 20, "grade": "A"},
    "Bob": {"age": 22, "grade": "B"},
    "Charlie": {"age": 19, "grade": "A"}
}

# Accessing Bob's grade
print(students["Bob"]["grade"])  # Output: B
'''
Code Text

Gemini
  1. Describe the time complexity of accessing elements in a dictionary?
  • In Python, accessing elements in a dictionary is very efficient because dictionaries are built on hash tables.

Time Complexity:

  • Average Case: O(1) → Constant time (direct lookup using key’s hash).

  • Worst Case: O(n) → Rare, happens only when many keys hash to the same index (hash collisions).

Code Text

Gemini
'''
my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict["b"])  # Access in O(1) time
'''
Code Text

Gemini
  1. In what situations are lists preferred over dictionaries?
  • Lists are preferred over dictionaries in Python when:

  • Order Matters – Lists maintain the order of elements, which is useful for sequences.

  • Index-based Access – When you want to access elements by position rather than a key.

  • Simple Collections – When you just need a collection of items without key–value mapping.

-Iteration Over All Elements – Easy to loop through elements in order.

  • Memory Efficiency for Small Data – Lists use less memory than dictionaries for simple sequential data.
Code Text

Gemini
'''
fruits = ["apple", "banana", "cherry"]
print(fruits[1])  # Output: banana  (access by index)
'''
Code Text

Gemini
  1. Why are dictionaries considered unordered, and how does that affect data retrieval?
  • Dictionaries in Python are considered unordered because they do not maintain the order of the keys as they were inserted. Instead, they store data in a way optimized for fast lookup using hashing.

How it affects data retrieval:

  • Direct Access by Key – You cannot rely on the order of keys; you must access values using their specific keys.

  • Iteration Order (pre-3.7) – Iterating over the dictionary may return keys in an arbitrary order.

  • No Indexing – Unlike lists, you cannot access dictionary items by position (e.g., dict[0] is invalid).

Code Text

Gemini
'''
my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
    print(key, my_dict[key])
'''
Code Text

Gemini
  1. Explain the difference between a list and a dictionary in terms of data retrieval. in pointers.
  • Here’s the difference between a list and a dictionary in terms of data retrieval, in pointers:

Access Method:

List → Access elements by index.

Dictionary → Access elements by key.

Speed:

List → Searching for a value takes O(n) time.

Dictionary → Key lookup is usually O(1) (very fast).

Order:

List → Maintains the order of elements.

Dictionary → Unordered (before Python 3.7); ordered by insertion (Python 3.7+).

Use Case:

List → Sequential data, iteration by position.

Dictionary → Fast access to values using meaningful keys.

Code Text

Gemini

Practical Questions

Code Text

Gemini
  1. Write a code to create a string with your name and print it?
Code Text

Gemini
'''
# Creating a string with your name
name = "Khushnoor Alam"

# Printing the string
print(name)   #output = Khushnoor Alam

'''
Code Text

Gemini
  1. Write a code to find the length of the string "Hello World".
Code Text

Gemini
'''
# String
text = "Hello World"

# Finding length
length = len(text)

# Printing the length
print("Length of the string:", length) #output = Length of the string: 11

'''
Code Text

Gemini
  1. Write a code to slice the first 3 characters from the string "Python Programming".
Code Text

Gemini
'''
# String
text = "Python Programming"

# Slicing the first 3 characters
first_three = text[:3]

# Printing the result
print(first_three) #output = Pyt

'''
Code Text

Gemini
  1. Write a code to convert the string "hello" to uppercase.
Code Text

Gemini
'''
# String
text = "hello"

# Converting to uppercase
upper_text = text.upper()

# Printing the result
print(upper_text)   #output = HELLO

'''
Code Text

Gemini
  1. Write a code to replace the word "apple" with "orange" in the string "I like apple".
Code Text

Gemini
'''
# Original string
text = "I like apple"

# Replacing "apple" with "orange"
new_text = text.replace("apple", "orange")

# Printing the result
print(new_text)          #output = I like orange

'''
Code Text

Gemini
  1. Write a code to create a list with numbers 1 to 5 and print it.
Code Text

Gemini
'''
# Creating a list
numbers = [1, 2, 3, 4, 5]

# Printing the list
print(numbers)       #output = [1, 2, 3, 4, 5]

'''
Code Text

Gemini
  1. Write a code to append the number 10 to the list [1, 2, 3, 4].
Code Text

Gemini
''' 
# Original list
numbers = [1, 2, 3, 4]

# Appending 10 to the list
numbers.append(10)

# Printing the updated list
print(numbers)           #output = [1, 2, 3, 4, 10]

'''
Code Text

Gemini
  1. P Write a code to remove the number 3 from the list [1, 2, 3, 4, 5].
Code Text

Gemini
'''
# Original list
numbers = [1, 2, 3, 4, 5]

# Removing the number 3
numbers.remove(3)

# Printing the updated list
print(numbers)   #output = [1, 2, 4, 5]

'''
Code Text

Gemini
  1. Write a code to access the second element in the list ['a', 'b', 'c', 'd'].
Code Text

Gemini
'''# List
letters = ['a', 'b', 'c', 'd']

# Accessing the second element (index 1)
second_element = letters[1]

# Printing the result
print(second_element)   #output = b

'''
Code Text

Gemini
  1. Write a code to reverse the list [10, 20, 30, 40, 50].
Code Text

Gemini
'''
# Original list
numbers = [10, 20, 30, 40, 50]

# Reversing the list
numbers.reverse()

# Printing the reversed list
print(numbers)    #output = [50, 40, 30, 20, 10]

'''
Code Text

Gemini
  1. Write a code to create a tuple with the elements 100, 200, 300 and print it.
Code Text

Gemini
'''
# Creating a tuple
numbers = (100, 200, 300)

# Printing the tuple
print(numbers)   #output = (100, 200, 300)

'''
Code Text

Gemini
  1. Write a code to access the second-to-last element of the tuple ('red', 'green', 'blue', 'yellow').
Code Text

Gemini
'''
# Tuple
colors = ('red', 'green', 'blue', 'yellow')

# Accessing the second-to-last element
second_last = colors[-2]

# Printing the result
print(second_last)   #output = blue

'''
Code Text

Gemini
  1. Write a code to find the minimum number in the tuple (10, 20, 5, 15).
Code Text

Gemini
'''
# Tuple
numbers = (10, 20, 5, 15)

# Finding the minimum number
min_number = min(numbers)

# Printing the result
print(min_number)   #output = 5


'''
Code Text

Gemini
  1. Write a code to find the index of the element "cat" in the tuple ('dog', 'cat', 'rabbit').
Code Text

Gemini
'''
# Tuple
animals = ('dog', 'cat', 'rabbit')

# Finding the index of "cat"
index_cat = animals.index('cat')

# Printing the result
print(index_cat)     #output = 1

'''
Code Text

Gemini
  1. Write a code to create a tuple containing three different fruits and check if "kiwi" is in it.
Code Text

Gemini
'''
# Creating a tuple
fruits = ('apple', 'banana', 'mango')

# Checking if "kiwi" is in the tuple
is_kiwi_present = 'kiwi' in fruits

# Printing the result
print(is_kiwi_present)   #output = False

'''
Code Text

Gemini
  1. Write a code to create a set with the elements 'a', 'b', 'c' and print it.
Code Text

Gemini
'''# Creating a set
letters = {'a', 'b', 'c'}

# Printing the set
print(letters)   #output = {'a', 'b', 'c'}

'''
Code Text

Gemini
  1. Write a code to clear all elements from the set {1, 2, 3, 4, 5}.
Code Text

Gemini
'''
# Original set
numbers = {1, 2, 3, 4, 5}

# Clearing the set
numbers.clear()

# Printing the empty set
print(numbers)   #output = set()

'''

Code Text

Gemini
  1. Write a code to remove the element 4 from the set {1, 2, 3, 4}.
Code Text

Gemini
'''
# Original set
numbers = {1, 2, 3, 4}

# Removing the element 4
numbers.remove(4)

# Printing the updated set
print(numbers)   #output = {1, 2, 3}

'''
Code Text

Gemini
  1. Write a code to find the union of two sets {1, 2, 3} and {3, 4, 5}.
Code Text

Gemini
'''
# Original set
numbers = {1, 2, 3, 4}

# Removing the element 4
numbers.remove(4)

# Printing the updated set
print(numbers)       #output = {1, 2, 3}

'''
Code Text

Gemini
  1. . Write a code to find the intersection of two sets {1, 2, 3} and {2, 3, 4}.
Code Text

Gemini
'''
# Two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}

# Finding intersection
intersection = set1 & set2  # or set1.intersection(set2)

# Printing the result
print(intersection)     #output ={2, 3}

'''
Code Text

Gemini
  1. Write a code to create a dictionary with the keys "name", "age", and "city", and print it.
Code Text

Gemini
'''
# Creating a dictionary
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Printing the dictionary
print(person)   #output = {'name': 'Alice', 'age': 25, 'city': 'New York'}

'''
Code Text

Gemini
  1. Write a code to add a new key-value pair "country": "USA" to the dictionary {'name': 'John', 'age': 25}.
Code Text

Gemini
'''# Original dictionary
person = {'name': 'John', 'age': 25}

# Adding new key-value pair
person['country'] = 'USA'

# Printing the updated dictionary
print(person)     #output = {'name': 'John', 'age': 25, 'country': 'USA'}

'''
Code Text

Gemini
  1. Write a code to access the value associated with the key "name" in the dictionary {'name': 'Alice', 'age': 30}.
Code Text

Gemini
'''
# Dictionary
person = {'name': 'Alice', 'age': 30}

# Accessing the value of key "name"
name_value = person['name']

# Printing the result
print(name_value)     #output = Alice

'''
Code Text

Gemini
  1. Write a code to remove the key "age" from the dictionary {'name': 'Bob', 'age': 22, 'city': 'New York'}.
Code Text

Gemini
'''# Original dictionary
person = {'name': 'Bob', 'age': 22, 'city': 'New York'}

# Removing the key "age"
person.pop('age')  # or del person['age']

# Printing the updated dictionary
print(person)      #output = {'name': 'Bob', 'city': 'New York'}

'''
Code Text

Gemini
  1. Write a code to check if the key "city" exists in the dictionary {'name': 'Alice', 'city': 'Paris'}.
Code Text

Gemini
'''
# Dictionary
person = {'name': 'Alice', 'city': 'Paris'}

# Checking if the key "city" exists
key_exists = 'city' in person

# Printing the result
print(key_exists)      #output = True

'''
Code Text

Gemini
  1. Write a code to create a list, a tuple, and a dictionary, and print them all.
Code Text

Gemini
''''# Creating a list
my_list = [1, 2, 3]

# Creating a tuple
my_tuple = (4, 5, 6)

# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25}

# Printing all
print("List:", my_list)
print("Tuple:", my_tuple)
print("Dictionary:", my_dict)      #output = List: [1, 2, 3]
Tuple: (4, 5, 6)
Dictionary: {'name': 'Alice', 'age': 25}

'''
Code Text

Gemini
  1. Write a code to create a list of 5 random numbers between 1 and 100, sort it in ascending order, and print the result.(replaced)
Code Text

Gemini
'''
import random

# Creating a list of 5 random numbers between 1 and 100
numbers = [random.randint(1, 100) for _ in range(5)]

# Sorting the list in ascending order
numbers.sort()

# Printing the sorted list
print(numbers)
#output = [12, 27, 45, 63, 88]

'''
Code Text

Gemini
  1. Write a code to create a list with strings and print the element at the third index.
Code Text

Gemini
'''
# Creating a list of strings
fruits = ["apple", "banana", "cherry", "date", "mango"]

# Accessing the element at index 3 (fourth element)
element = fruits[3]

# Printing the result
print(element)
#output = date

'''
Code Text

Gemini
  1. Write a code to combine two dictionaries into one and print the result.
Code Text

Gemini
'''
# Two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Combining dictionaries
combined_dict = {**dict1, **dict2}  # Using dictionary unpacking

# Printing the result
print(combined_dict)
#output =  {'a': 1, 'b': 2, 'c': 3, 'd': 4}

'''
Code Text

Gemini
  1. Write a code to convert a list of strings into a set.
Code Text

Gemini
Code Text

Gemini

Code Text

Gemini

Code Text

Gemini

Code Text

Gemini

Double-click (or enter) to edit

Code Text

Gemini

Double-click (or enter) to edit

Code Text

Gemini

Code Text

Gemini

Code Text

Gemini
2. Write a code to find the length of the string "Hello World".
Code Text

Gemini

Code Text

Gemini

Code Text

Gemini

Double-click (or enter) to edit

Code Text

Gemini

Code Text

Variables Terminal
Add a comment